import 'dart:convert';
import 'dart:typed_data';

import 'package:encrypt/encrypt.dart';

class Validators {
  static String? validateUsername(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入用户名';
    }
    return null;
  }

  static String? validatePassword(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入密码';
    }
    if (value.length < 6) {
      return '密码长度不能少于6位';
    }
    return null;
  }

  static String? validateEmail(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入邮箱';
    }
    final emailRegExp = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    if (!emailRegExp.hasMatch(value)) {
      return '请输入有效的邮箱地址';
    }
    return null;
  }

  /// 解密函数（等效于 Objective-C 的 vhbsjiemi 方法）
  String decryptVhbs(String hexStr, String hexKey) {
    final keyBytes = hexToBytes(hexKey);
    final encryptedBytes = hexToBytes(hexStr);

    final key = Key(keyBytes);
    final encrypter = Encrypter(AES(key, mode: AESMode.ecb, padding: 'PKCS7'));

    final decrypted = encrypter.decrypt(
      Encrypted(encryptedBytes),
      iv: IV(Uint8List(0)),
    ); // ECB 不需要 IV
    return decrypted;
  }

  /// 将十六进制字符串转为 Uint8List
  Uint8List hexToBytes(String hex) {
    final result = Uint8List(hex.length ~/ 2);
    for (var i = 0; i < hex.length; i += 2) {
      result[i ~/ 2] = int.parse(hex.substring(i, i + 2), radix: 16);
    }
    return result;
  }

  /// Uint8List转十六进制字符串
  static String _bytesToHex(List<int> bytes) {
    final buffer = StringBuffer();
    for (var byte in bytes) {
      buffer.write(byte.toRadixString(16).padLeft(2, '0'));
    }
    return buffer.toString();
  }

  String vhbsJiami(String vhbsStr, String vhbsKey) {
    final keyBytes = hexToBytes(vhbsKey);
    final key = Key(keyBytes);

    final encrypter = Encrypter(AES(key, mode: AESMode.ecb, padding: 'PKCS7'));

    final plainText = utf8.encode(vhbsStr);
    final encrypted = encrypter.encryptBytes(plainText, iv: IV.fromLength(0));

    return _bytesToHex(encrypted.bytes);
  }
}
